package cc.mcyx.ychat.fillter

import cn.hutool.json.JSONObject
import org.springframework.core.MethodParameter
import org.springframework.http.MediaType
import org.springframework.http.converter.HttpMessageConverter
import org.springframework.http.server.ServerHttpRequest
import org.springframework.http.server.ServerHttpResponse
import org.springframework.http.server.ServletServerHttpResponse
import org.springframework.web.bind.annotation.ControllerAdvice
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice

@ControllerAdvice
class ResponseFilter : ResponseBodyAdvice<Any> {
    override fun supports(p0: MethodParameter, p1: Class<out HttpMessageConverter<*>>): Boolean {
        return true
    }

    override fun beforeBodyWrite(
        p0: Any?,
        p1: MethodParameter,
        p2: MediaType,
        p3: Class<out HttpMessageConverter<*>>,
        p4: ServerHttpRequest,
        p5: ServerHttpResponse
    ): Any {
        // 针对 /api/ 特殊规范化
        if (p4.uri.toURL().toString().contains("/api/")) {
            // 规范化响应格式
            val code = (p5 as ServletServerHttpResponse).servletResponse.status
            if (code != 200) return p0 ?: p5.close()
            val json = JSONObject().apply {
                set("code", code)
                set("data", p0)
                set("message", "ok")
            }
            // 对 String 做点特殊处理
            if (p1.method?.returnType == String::class.java) return json.toString()
            return json
        }
        // 按默认情况走
        return p0!!
    }

}